package com.asa.common.arouter

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter
import java.lang.NullPointerException

class ARoutImplManager private constructor(){

    companion object{
        val INSTANCE : ARoutImplManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){ ARoutImplManager()}
    }


    fun build(targetPath:String):RouterConfig{
        val routerConfig = RouterConfig()
        routerConfig.setTarget(targetPath)
        return routerConfig
    }

    class RouterConfig{

        private var source:String = ARouterConfig.MAIN_ACTIVITY_MAIN

        private var target:String = ""

        private var bundle : Bundle?= null

        fun setSource(source:String):RouterConfig{
            this.source = source
            return this
        }

        fun setTarget(target:String):RouterConfig{
            this.target = target
            return this
        }
        fun setBundle(bundle:Bundle):RouterConfig{
            this.bundle = bundle
            return this
        }

        fun createFragment():Fragment{
            val fragment = ARouter.getInstance()
                .build(target)
                .withAction(source)
                .withBundle(ARouterConfig.AROUTER_BUNDLE_KEY,bundle)
                .navigation()
            if (fragment == null || fragment !is Fragment){
                throw NullPointerException("查找fragment失败,请检车key是否配置")
            }
            return fragment
        }

        fun navigationForResult(activity:AppCompatActivity,requestCode:Int):Any{
            return ARouter.getInstance()
                .build(target)
                .withAction(source)
                .withBundle(ARouterConfig.AROUTER_BUNDLE_KEY,bundle)
                .navigation(activity,requestCode)
        }

        fun navigation():Any?{
            return ARouter.getInstance()
                .build(target)
                .withAction(source)
                .withBundle(ARouterConfig.AROUTER_BUNDLE_KEY,bundle)
                .navigation()
        }


    }


}